<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.main }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.item }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="description"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑角色信息" placement="top-start" :enterable="false">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除角色信息" placement="top-start" :enterable="false">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色权限" placement="top-start" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showDisDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed" :close-on-click-modal="false">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <template>
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="description">
                <el-input v-model="addForm.description"></el-input>
              </el-form-item>
              <el-form-item label="关键字" prop="keyword">
                <el-input v-model="addForm.keyword" placeholder="请输入 HAS_ + 大写字母 形式"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-tab-pane>
        <el-tab-pane label="分配权限" name="second">
          <el-table :data="rightsList" height="250" border stripe style="width: 100%" @selection-change="selectedChange">
            <el-table-column prop="id" type="selection"></el-table-column>
            <el-table-column type="index" label="序列"></el-table-column>
            <el-table-column prop="rightName" label="权限名称"></el-table-column>
            <el-table-column prop="keyword" label="角色关键字"> </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色信息对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" destroy-on-close :visible.sync="disDialogVisible" width="50%" @close="disDialogVisible = false" :close-on-click-modal="false">
      <!-- 显示当前角色基本信息 -->
      <div>
        <el-tag type="primary" effect="dark" class="tag">当前角色: {{ role.roleName }}</el-tag>
        <el-tag type="info" effect="dark">描述: {{ role.description }}</el-tag>
      </div>
      <!-- 分配权限区 -->
      <el-table style="width: 100%" :data="rightsList" height="250" ref="disTable" border stripe @selection-change="selectedChange">
        <template>
          <el-table-column prop="id" type="selection"></el-table-column>
          <el-table-column prop="rightName" label="权限名称"></el-table-column>
          <el-table-column prop="keyword" label="角色关键字"> </el-table-column>
        </template>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="disDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="distribution">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证关键字的规则
    var checkKeyword = (rule, value, cb) => {
      const regKeyword = /^HAS_[A-Z]{0,5}$/
      return regKeyword.test(value) ? cb() : cb(new Error('请输入合法的关键字'))
    }
    return {
      // 面包屑导航标题
      menuTitle: {
        main: '',
        item: ''
      },
      // 角色列表
      rolesList: [],
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色表单数据
      addForm: {
        roleName: '',
        desription: '',
        keyword: ''
      },
      // 添加角色表单校验规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入关键字', trigger: 'blur' },
          { min: 5, max: 9, message: '长度在 5 到 9 个字符', trigger: 'blur' },
          { validator: checkKeyword, trigger: 'blur' }
        ]
      },
      // 添加角色时所分配的权限
      rightsId: [],
      // 添加对话框的面签切换
      activeName: 'first',
      // 权限列表
      rightsList: [],
      // 编辑角色信息表单数据
      editForm: {},
      // 控制编辑角色信息对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑角色信息表单数据校验规则
      editFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在 2 到 6 个字符', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      disDialogVisible: false,
      // 当前行角色
      role: {}
    }
  },
  created() {
    this.getMenuList()
    this.getRoleList()
  },
  methods: {
    // 获取面包屑导航标题
    async getMenuList() {
      const { data: res } = await this.$axios.get('/menu/getMenuList.do')
      if (!res.flag) return this.$message.error(res.message)
      // 获取当前激活路径
      const activePath = window.sessionStorage.getItem('activePath')
      // console.log(activePath)
      // 循环判断激活路径对应的路径名称
      res.data.forEach(value => {
        value.menuItem.forEach(item => {
          if (item.path === activePath) {
            this.menuTitle.item = item.title
            this.menuTitle.main = value.title
          }
        })
      })
    },
    // 获取角色列表
    async getRoleList() {
      const { data: res } = await this.$axios.get('/role/findAll.do')
      if (!res.flag) return this.$message.error(res.flag)
      this.rolesList = res.data
    },
    // 展示添加角色对话框
    async showAddDialog() {
      this.addDialogVisible = true

      // 发送请求, 获取权限列表
      const { data: rs } = await this.$axios.get('/right/findAll.do')
      if (!rs.flag) return this.$message.error(rs.message)
      this.rightsList = rs.data
    },
    // 选择发生变化
    selectedChange(selection) {
      this.rightsId = []
      selection.forEach(value => {
        this.rightsId.push(value.id)
      })
    },
    // 添加角色对话框关闭
    addDialogClosed() {
      // 重置表单数据
      this.$refs.addFormRef.resetFields()
      this.rightsId = []
    },
    // 添加角色
    addRole() {
      // 验证表单数据
      this.$refs.addFormRef.validate(async valid => {
        // 校验不通过
        if (!valid) return false
        // 判断是否已经分配权限
        if (this.rightsId.length <= 0 || this.rightsId === null) return this.$message.warning('请分配该角色的权限')

        // 发送请求, 添加角色
        const { data: res } = await this.$axios.post('/role/add.do?rightsId=' + this.rightsId, this.addForm)
        if (!res.flag) return this.$message.error(res.message)
        this.$message.success(res.message)

        this.getRoleList()
        this.addDialogVisible = false
      })
    },
    // 删除角色
    async deleteRole(id) {
      // 防止用户误操作
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)

      if (result !== 'confirm') return this.$message.info('已经取消删除')

      // 发送请求, 删除角色
      const { data: res } = await this.$axios.delete(`/role/delete.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.getRoleList()
    },
    // 展示编辑角色对话框
    async showEditDialog(id) {
      // 发送请求, 回显当前角色基本信息
      const { data: res } = await this.$axios.delete(`/role/getRoleById.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)
      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 编辑角色信息对话框关闭事件
    editDialogClosed() {
      // 重置表单数据
      this.$refs.editFormRef.resetFields()
    },
    // 修改角色信息
    editRole() {
      // 验证表单数据
      this.$refs.editFormRef.validate(async valid => {
        // 校验不通过
        if (!valid) return false

        // 发送请求, 将修改后的角色信息上传到后台
        const { data: res } = await this.$axios.post('/role/edit.do', this.editForm)
        if (!res.flag) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 刷新角色列表
        this.getRoleList()
        this.editDialogVisible = false
      })
    },
    // 展示分配权限对话框
    async showDisDialog(row) {
      this.disDialogVisible = true

      // 发送请求, 获取权限列表
      const { data: res } = await this.$axios.get('/right/findAll.do')
      if (!res.flag) return this.$message.error(res.message)
      this.rightsList = res.data

      // 方便分配权限
      this.role = row

      // 发送请求, 获取当前角色拥有的权限
      const { data: rs } = await this.$axios.get(`/role/findRightsByRoleId.do?id=${row.id}`)
      console.log(res)
      if (!rs.flag) return this.$message.error(rs.message)
      this.rightsId = rs.data

      // 默认选中已有权限
      this.$nextTick(() => {
        this.rightsId.forEach(id => {
          this.$refs.disTable.toggleRowSelection(this.rightsList.find(item => item.id === id))
        })
      })
    },
    // 分配权限
    async distribution() {
      // 发送请求, 为当前角色分配的权限上传
      const { data: res } = await this.$axios.put(`/role/setDistribution.do?id=${this.role.id}`, this.rightsId)
      if (!res.flag) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.disDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin-left: 50px;
}

.tag {
  margin-right: 150px;
}
</style>
